from PyQt5.QtWidgets import QWidget, QFormLayout, QComboBox, QSpinBox, QPushButton, QLabel, QFileDialog
from PyQt5.QtCore import pyqtSignal

class ConfigPanel(QWidget):
    apply_requested = pyqtSignal(dict)

    def __init__(self, config_data, offline_mode=False):
        super().__init__()
        self.config_data = config_data
        self.offline_mode = offline_mode
        self.layout = QFormLayout(self)
        self.init_ui()

    def init_ui(self):
        self.default_entry = QComboBox()
        self.default_entry.setEditable(True)
        self.default_entry.addItems(["0", "Advanced options for Ubuntu"])
        self.default_entry.setCurrentText(self.config_data.get("GRUB_DEFAULT", "0"))
        self.layout.addRow("默认启动项", self.default_entry)

        self.timeout = QSpinBox()
        self.timeout.setRange(0, 60)
        self.timeout.setValue(int(self.config_data.get("GRUB_TIMEOUT", "5")))
        self.layout.addRow("超时时间 (秒)", self.timeout)

        self.cmdline_linux = QLineEdit(self.config_data.get("GRUB_CMDLINE_LINUX", ""))
        self.layout.addRow("内核参数", self.cmdline_linux)

        self.apply_button = QPushButton("应用更改")
        self.apply_button.clicked.connect(self.emit_config)
        self.layout.addRow(self.apply_button)

        if self.offline_mode:
            self.export_button = QPushButton("导出配置文件")
            self.export_button.clicked.connect(self.export_config)
            self.layout.addRow(self.export_button)

    def emit_config(self):
        new_config = {
            "GRUB_DEFAULT": self.default_entry.currentText(),
            "GRUB_TIMEOUT": str(self.timeout.value()),
            "GRUB_CMDLINE_LINUX": self.cmdline_linux.text()
        }
        self.apply_requested.emit(new_config)

    def export_config(self):
        path, _ = QFileDialog.getSaveFileName(self, "导出 GRUB 配置", "", "GRUB 配置文件 (*.cfg)")
        if path:
            parser = GrubConfigParser(simulate_mode=True)
            parser.config_data.update({
                "GRUB_DEFAULT": self.default_entry.currentText(),
                "GRUB_TIMEOUT": str(self.timeout.value()),
                "GRUB_CMDLINE_LINUX": self.cmdline_linux.text()
            })
            parser.save_to_file(path)